package com.efeichong.project.service.impl;

import com.efeichong.oss.LocalOssService;
import com.efeichong.oss.OssFactory;
import com.efeichong.oss.OssType;
import com.efeichong.project.service.OssService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lxk
 * @date 2020/12/3
 * @description
 */
@RequiredArgsConstructor
@Service
public class OssServiceImpl implements OssService {

    private final OssFactory ossFactory;

    /**
     * 文件上传
     *
     * @param file
     * @param folderName
     * @param suffix
     * @return
     */

    @Override
    public String upload(MultipartFile file, String folderName, String suffix) {
//        TxOssService ossService = ossFactory.create(OssType.TX);
//        String url = ossService.upload(file, bucketName, folderName,suffix);
//        return url;
        OssService ossService = ossFactory.create(OssType.LOCAL);
        String url = ossService.upload(file, folderName, suffix);
        return url;
    }


    /**
     * 文件下载
     *
     * @param url
     * @param response
     */
    @Override
    @SneakyThrows
    public void download(String url, HttpServletResponse response) {
        LocalOssService ossService = ossFactory.create(OssType.LOCAL);
        byte[] bytes = ossService.download(url);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
    }


    /**
     * 文件删除
     *
     * @param url
     */
    @Override
    public void delete(String url) {
        LocalOssService ossService = ossFactory.create(OssType.LOCAL);
        ossService.delete(url);
    }
}
